package com.ruoyi.common.utils.tt;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.tt.date.SmartDateConverter;
import com.ruoyi.common.utils.tt.model.CelebrityBasicInfo;

import java.text.ParseException;
import java.util.Date;

public class ApiGetInfoUtil {
    private static final String API_URL = "https://baike.baidu.com/api/openapi/BaikeLemmaCardApi";
    private static final String DEFAULT_PARAMS = "scope=103&format=json&appid=379020";
    private static final int MAX_RETRY_COUNT = 10;
    private static final long RETRY_INTERVAL = 2000; // 5秒

    public static void main(String[] args) {
        System.out.println(getBirthdayByName("张鑫"));
    }

    public static Date getBirthdayByName(String name) {
        String splicingStr = DEFAULT_PARAMS + "&bk_key=" + name;
        int retryCount = 0;

        while (retryCount < MAX_RETRY_COUNT) {
            try {
                String result = HttpUtils.sendGet(API_URL, splicingStr);
                if (result.contains("errno")){
                    throw new RuntimeException("请求异常");
                }
                CelebrityBasicInfo celebrityBasicInfo = JsonUtils.parseObject(result, CelebrityBasicInfo.class);
                Date date = SmartDateConverter.convertToDate(celebrityBasicInfo.getValueByKey("bornDay"));
                return date;
            } catch (Exception e) {
                retryCount++;
                if (retryCount >= MAX_RETRY_COUNT) {
                    throw new RuntimeException("Failed after " + MAX_RETRY_COUNT + " retries", e);
                }

                try {
                    Thread.sleep(RETRY_INTERVAL);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Retry interrupted", ie);
                }
            }
        }

        throw new RuntimeException("Unexpected error in getBirthdayByName");
    }
}
